var actpro_contentsbill = require('../../model/pro_contents')
// var actcart = require('../../sys/cart')
var actcart = require('../../../../xc/sys/purchaseorder')
var timejs = require('../../model/time')

var app = getApp();
Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    integralname: {
      type: String,
      default: '积分'
    },
    attrStyle: {
      type: Object,
      default: ''
    },
    customBuybuttonStyle: { //立即购买样式
      type: String,
      default: ''
    },
    customAddbuttonStyle: { //加入购物车样式
      type: String,
      default: ''
    },
    customChoosedStyle: { //已选择样式
      type: String,
      default: ''
    },
    customPopupStyle: { //弹出层样式
      type: String,
      default: ''
    },
    customUnchoosedStyle: { //未选择样式
      type: String,
      default: ''
    },
    imgmode: { //图片模式 big 大图 small小图
      type: String,
      default: 'big'
    },
    btntype: { //按钮类型 square round
      type: String,
      default: 'square'
    },
    color: { //主色
      type: String,
      default: '#333333'
    },
    icon: { //图标名
      type: String,
      default: 'close'
    },
    mainimgshow: { //主图显示
      type: Boolean,
      default: true
    },
    nameshow: { //标题显示
      type: Boolean,
      default: true
    },
    pricecolor: { //价格颜色
      type: String,
      default: '#333333'
    },
    markpricecolor: { //划线价格颜色
      type: String,
      default: '#999999'
    },
    subcolor: { //副颜色
      type: String,
      default: '#333333'
    },
    titlecolor: { //标题颜色
      type: String,
      default: '#333333'
    },
    // btype: { //底部样式
    //   type: Number,
    //   value: 3,
    //   observer: function (newVal, oldVal) {
    //     this.setData({
    //       btype: newVal,
    //     })
    //   }
    // },

  },

  /**
   * 组件的初始数据
   */
  data: {
    attrcss: {
      bottom: {
        css: "",
        btncartcss: "",
        btnbuycss: ""
      }
    },
    popupblock: true,
    objmodel: null,
    shadestatus: false,
    activityid: 0,
    groupid: "",
    wsgrade: 0,
    oneattr: 0
    // selected: {
    //   cid: 1,
    //   num: 1,
    //   attrs: [],
    //   stock: 0,
    //   price: -1,
    //   realprice: -1,
    //   flag: -1, //最后一列未选中
    //   pnum: -2
    // },
  },
  ready: function () {

  },
  /**
   * 组件的方法列表
   */
  methods: {
    // id产品id, activityid活动id,atype活动类型,type底部样式 1加购 2立即购买 3两种 ,selected已选
    setpro(options) {
      var that = this;
      var id = options.proid;
      var selected = options.selected;
      var activityid = 0;
      var activitytype = 0;
      var wsgrade = options.wsgrade; //批发等级

      this.setData({
        wsgrade: wsgrade,
        btype: options.type, //事件类型 1加购 2立即购买
        objmodel: null,
        shadestatus: true,
        selected: { //已选择
          proid: id, //商品id
        }
      });

      actpro_contentsbill.showproinfo(id, activityid, activitytype).then(function (paradata) {


        if (paradata["status"] == 1) {
          var objmodel = paradata["obj"]
          var updatemodel = {
            objmodel: objmodel
          }
          updatemodel["selected.presaletime"] = objmodel["presaletime"];

          updatemodel["selected.name"] = objmodel["name"];
          updatemodel["selected.guigetype"] = objmodel["guigetype"];

          if (paradata["obj"]["guigetype"] == "-1") {
            //   updatemodel["selected.stock"] = paradata["obj"]["stock"];           
            //   updatemodel["selected.weight"] = paradata["obj"]["weight"];
            //   updatemodel["selected.realprice"] = paradata["obj"]["realprice"];
            //   updatemodel["selected.price"] = paradata["obj"]["price"];
            var item = {
              stock: objmodel["stock"],
              weight: objmodel["weight"],
              realprice: objmodel["realprice"],
              price: objmodel["price"],
              num: 1
            }
            var agent = paradata["obj"]["agent"];
            if (agent['status'] == 1) {
              if (agent['calc'] == 'fixed') {
                item["wsprice"] = paradata["obj"]["agent"]['data'][0][wsgrade];
              } else {


                item["wsprice"] = paradata["obj"]["realprice"] * paradata["obj"]["agent"]['data'][0][wsgrade] * 0.0001;

              }
            } else {
              console.log(app.globalData.configdata.wholesale.agent)

              var agent = app.globalData.configdata.wholesale.agent;
              var discount = agent.grade[wsgrade].discount
              item["wsprice"] = paradata["obj"]["realprice"] * discount * 0.01
            }
            var attrs = {
              '-1': item
            }

            updatemodel["selected.attrs"] = attrs;

          } else {


            // updatemodel["selected.stock"] = -1;
            // updatemodel["selected.weight"] = -1;
            var agent = objmodel['agent'];
            var attrs = objmodel['skuht'];

            if (agent['status'] == 1) {
              if (agent['calc'] == 'fixed') {
                var i = 0;
                for (var k in attrs) {
                  attrs[k]['num'] = 0;
                  attrs[k]['key'] = k.split("_")
                  attrs[k]['wsprice'] = agent['data'][i][wsgrade];
                  i++;
                }
              } else {
                var s = 0;
                for (var k in attrs) {
                  attrs[k]['num'] = 0;
                  attrs[k]['key'] = k.split("_")
                  attrs[k]['wsprice'] = attrs[k]["realprice"] * agent['data'][s][wsgrade] * 0.0001;
                  s++;
                }
              }
            } else {
              var sysagent = app.globalData.configdata.wholesale.agent;
              var discount = sysagent.grade[wsgrade].discount
              for (var t in attrs) {
                attrs[t]['num'] = 0;
                attrs[t]['key'] = t.split("_")
                attrs[t]['wsprice'] = (attrs[t]["realprice"] * discount * 0.01).toFixed(0);
              }
            }

            updatemodel["selected.attrs"] = attrs;
          }

          that.setData(updatemodel)
          that.changeproprice()

        }
      }).then(function () {
        that.getselected()

      })
    },


    changeoneattr(e) {
      var dataset = e.currentTarget.dataset;
      var index = dataset.index;
      if (this.data.oneattr != index) {
        this.setData({
          oneattr: index
        })
      }
    },
    makeprice() {
      
      var totalprice = 0;
      var type = 0;
      var nums = 0;
      var selected = this.data.selected;
      console.log("makeprice")

      console.log(selected)
      if (selected.guigetype == 1) {
        var attrs = selected.attrs;
        for (var i in attrs) {
          if (attrs[i]['num'] >= 1) {
            type += 1;
            nums += attrs[i]['num'];
            totalprice += (attrs[i]['actprice'] ? attrs[i]['actprice'] : attrs[i]['wsprice']) * attrs[i]['num']
          }
        }
      } else {
        type = 1;
        nums = selected.attrs['-1'].num
        totalprice += (selected.attrs['-1']['actprice'] ? selected.attrs['-1']['actprice'] : selected.attrs['-1']['wsprice']) * selected.attrs['-1']['num']

      }

      this.setData({
        'selected.totalprice': totalprice,
        'selected.type': type,
        'selected.nums': nums,
      })


    },
    // 更新数量
    updatenum(e) {

      var key = e.currentTarget.dataset.key
      var val = parseInt(e.detail);
      var selected = this.data.selected

      if (this.data.nowactivity) {
        var allnum = 0;
        for (var i in selected['attrs']) {
          if (key != i) {
            allnum += selected['attrs'][i]['num']
          }
        }
        var maxnum = this.data.nowactivity.stock - allnum
        if (maxnum < val) {
          wx.showToast({
            icon: "none",
            title: '已超出最大活动库存',
          })
          val = maxnum
        }
      }
      selected['attrs'][key]['num'] = -1
      this.setData({
        'selected': selected
      })
      selected['attrs'][key]['num'] = val

      this.setData({
        'selected': selected
      })
      

      this.makeprice()
    },
    changeproprice() {
      var xcmodel = this.data.objmodel
      var activity = xcmodel.activity;
      console.log()
      if (activity && activity.status == 1) {
        var list = activity.actlist;
        var nowactivity = ''
        for (var i in list) {
          var item = list[i]
          var status = timejs.timestatus(item.acttime[0], item.acttime[1])
          item['actstatus'] = status;
          switch (status) {
            case "end": {
              item['stock'] = 0;
              break;
            }
            case "unstart": {
              var num = item['num'] * (xcmodel.stock * 1 + xcmodel.salesvolume * 1) * 0.01
              item['stock'] = num.toFixed(0)
              break;
            }
            case "ing": {
              var percent = list[i]['num'] * 1;
              var listnum = list.length
              for (var a = 0; a < listnum; a++) {
                if (timejs.timestatus(list[a].acttime[0], list[a].acttime[1]) == 'end') {
                  percent += list[a]['num'] * 1
                }
              }

              var num = percent * (xcmodel.stock * 1 + xcmodel.salesvolume * 1) * 0.01 - xcmodel.salesvolume;
              num = num.toFixed(0);
              if (num < 0) {
                item['stock'] = 0
              } else {
                item['stock'] = num
              }
              if (!nowactivity) {
                nowactivity = item
              }
              break;
            }
          }
        }
        if (nowactivity) {
          var selected = this.data.selected;
          var discount = nowactivity['discount']
          var attrs = selected.attrs
          for (var i in attrs) {
            attrs[i]['actprice'] = (discount * attrs[i].wsprice * 0.01).toFixed(0);
          }

          this.setData({
            btype:2,
            nowactivity: nowactivity,
            'selected.attrs': attrs
          })

        }
      }
    },
    getcache(key) {
      var selected = this.data.selected
      var that = this;

      wx.getStorage({
        key: key,
        success: function (e) {
          if (e.data) {
            var obj = JSON.parse(e.data);
            if (obj[selected.proid]) {
              for (var i in selected.attrs) {
                if (obj[selected.proid][i]) {
                  selected.attrs[i]['num'] = obj[selected.proid][i]
                }

              }
            }
            that.setData({
              selected: selected
            })

            that.makeprice()
            console.log(e.data)
          }

        },
        fail: function (e) {

          that.makeprice()
        }
      })
    },
    setcache(key) {
      var that = this;
      var selected = this.data.selected

      wx.getStorage({
        key: key,
        success: function (e) {
          console.log(e)
          if (e.data) {
            var objs = JSON.parse(e.data)
            objs[selected.proid] = that.changeattr(selected.attrs);
            that._setcache(key, objs)
          }
        },
        fail: function (e) {
          var obj = {};
          obj[selected.proid] = that.changeattr(selected.attrs);
          that._setcache(key, obj)
        }
      })
    },
    changeattr(attrs) {
      var newattrs = {};
      for (var i in attrs) {
        newattrs[i] = attrs[i]['num']
      }

      return newattrs
    },
    _setcache(key, obj) {
      wx.setStorage({
        key: key,
        data: JSON.stringify(obj),
        success: function (et) {}
      })
    },
    getselected() {
      var that = this

      var selected = this.data.selected

      // if (app.globalData.purchaseorder && app.globalData.purchaseorder[selected.proid]) {
      //   var objs = app.globalData.purchaseorder
      //   console.log("dddddddddddddddddddd")
      //   console.log(objs)
      //   console.log(selected.attrs)

      //   for (var i in selected.attrs) {
      //     if (objs[selected.proid][i]) {
      //       selected.attrs[i]['num'] = objs[selected.proid][i]['num']
      //     }
      //   }
      //   console.log("dddddddddddddddddddd")
      //   console.log(selected)

      //   that.setData({
      //     selected: selected
      //   })
      // } else
      if (app.globalData.wsadd) {
        var obj = app.globalData.wsadd
        if (obj[selected.proid]) {
          for (var i in selected.attrs) {
            if (obj[selected.proid][i]) {
              selected.attrs[i]['num'] = obj[selected.proid][i]
            }
          }
        }
        that.setData({
          selected: selected
        })
      }

      that.makeprice()

    },
    setselected() {
      var that = this
      var selected = this.data.selected
      var obj = {}
      if (app.globalData.wsadd) {
        obj = app.globalData.wsadd
      }
      obj[selected.proid] = that.changeattr(selected.attrs);
      app.globalData.wsadd = obj
    },
    onCloseShade() {
      this.setselected()
      this.setData({
        shadestatus: false
      });
    },
    chageshadestatus: function (e) {
      var dataset = e.currentTarget.dataset;
      if (dataset["cid"]) {
        this.data.selected.cid = dataset.cid;
      }


      if (dataset.value == "1") {
        this.setData({
          shadestatus: true
        });
      } else {
        this.setData({
          shadestatus: false
        });

      }

    },
    enlarge(e) {
      var dataset = e.currentTarget.dataset;
      var imgsdatas = [];
      for (var i in dataset.imgs) {
        imgsdatas.push(dataset.imgs[i]['simg'])
      }
      wx.previewImage({
        current: dataset.imgs[dataset.index]['simg'], // 当前显示图片的http链接  
        urls: imgsdatas // 需要预览的图片http链接列表  
      })
    },
    //浏览图片
    previewImage: function (e) {
      var that = this;
      var current = e.target.dataset.src;
      var imgsdata = [];
      imgsdata.push(current);
      wx.previewImage({
        current: current, // 当前显示图片的http链接  
        urls: imgsdata // 需要预览的图片http链接列表  
      })
    },
    //弹出框
    popup: function (e) {
      this.setData({
        popupblock: false
      })
    },
    //关闭弹窗
    closepop: function () {
      var that = this;
      that.setData({
        popupblock: true
      })
    },

    // 选择属性颜色
    chooseattr(e) {

      var updatemodel = {};
      var dataset = e.currentTarget.dataset;
      var one_index = dataset.one_index; //第组
      var two_index = dataset.two_index; //组内每几个元素
      var two_name = dataset.two_name;
      var selected = this.data.selected;
      var skudata = this.data.objmodel["skudata"];
      var skuht = this.data.objmodel["skuht"];


      if (selected["attrs"][one_index]["keyval"] == two_index) {
        selected["attrs"][one_index]["keyval"] = -1;
        selected["attrs"][one_index]["keyname"] = "";
      } else {
        selected["attrs"][one_index]["keyval"] = two_index;
        selected["attrs"][one_index]["keyname"] = two_name;
      }
      var pnum = 0;
      var flag = -1; //用来标记最后一个未选的
      var arrkeys = [];
      var updatemodel = {};
      var temval = [];
      //pnum 判断有几个款未选中，如果只剩下一个属性未选择判断缺货
      for (var a in selected["attrs"]) {
        //取选中的值
        temval.push(selected["attrs"][a]["keyval"]);

        if (selected["attrs"][a]["keyval"] == -1) {
          pnum--;
          if (pnum == -2) {
            break;
          }
          flag = a;
        }
      }
      if (pnum == 0 || pnum == -1) {
        var len = temval.length;
        temval.forEach(function (val, i) {

          var newmodel = {
            "startkey": temval.slice(0, i),
            "endkey": []
          };
          if (i < len - 1) {
            newmodel["endkey"] = temval.slice((i + 1), len)
          }
          arrkeys.push(newmodel)
        })
        for (var i = 0, ilen = arrkeys.length; i < ilen; i++) {
          if (arrkeys[i]["startkey"].length > 0) {
            arrkeys[i]["startkey"] = arrkeys[i]["startkey"].join("_") + "_";
          } else {
            arrkeys[i]["startkey"] = "";
          }

          if (arrkeys[i]["endkey"].length > 0) {
            arrkeys[i]["endkey"] = "_" + arrkeys[i]["endkey"].join("_");
          } else {
            arrkeys[i]["endkey"] = "";
          }
        }
      }

      if (pnum == 0) {
        var actattr = skuht[temval.join("_")]
        selected["price"] = actattr["price"];
        if (this.data.rewordid == 0) {
          selected["realprice"] = actattr["realprice"];
        } else {
          selected["realprice"] = 0;
        }
        selected["stock"] = actattr["stock"];
        selected["weight"] = actattr["weight"];
        selected["activityprice"] = actattr["activityprice"];
        //不限量
        if (actattr["stock"] != -100 && parseInt(selected["num"]) > actattr["stock"]) {
          selected["num"] = actattr["stock"];
        }
        // var limitinfo =that.data.objmodel.limitinfo
        // if(limitinfo&&limitinfo.limitnum>-1 &&selected.num >parseInt(limitinfo.limitnum)){
        // wx.showToast({
        //   title: '限购' + limitinfo.limitnum + "件",
        // })
        // selected["num"]=limitinfo.limitnum
        // return ;
        // }
      } else {
        //未设价格
        selected["price"] = -1
        selected["realprice"] = -1
      }
      selected["flag"] = flag;
      selected["pnum"] = pnum;
      updatemodel["arrkeys"] = arrkeys;
      updatemodel["selected"] = selected;

      selected['proid'] = this.data.objmodel.id

      this.setData(updatemodel)

      var myEventDetail = selected // detail对象，提供给事件监听函数
      var myEventOption = {} // 触发事件的选项


      this.triggerEvent('attrchoose', myEventDetail, myEventOption)
    },




    confirmselected(e) {
      var dataset = e.currentTarget.dataset;
      var that = this;
      var selected = this.data.selected;
      var buytype = dataset.buytype; //1加购 2立即买
      // var objmodel = that.data.objmodel;
      console.log("selected.nums")
      console.log(selected.nums)

      if (selected.nums <= 0) {
        wx.showToast({
          icon: "error",
          title: '请至少选择一件',
        })
        return false
      }

      if (buytype == 1) {
        actcart.cartadd(selected);
        this.setData({
          shadestatus: false
        });
        wx.showToast({
          title: '加购成功',
        })
      } else {
        console.log(this.data.objmodel)
        console.log(this.data.selected)

        var obj = this.data.objmodel;
        var attrs = this.data.selected.attrs;
        var arr = ['agent', 'about', 'guigetype', 'id', 'name', 'price', 'realprice', 'simg', 'skudata', 'skuht', 'stock', 'unit', 'presaletime']
        var newmodel = {}

        for (var i in arr) {
          newmodel[arr[i]] = obj[arr[i]]
        }

        var newattr = {}
        for (var a in attrs) {
          if (attrs[a]['num'] > 0) {
            newattr[a] = attrs[a]
          }
        }

        newmodel['attrs'] = newattr
        console.log("newmodel")
        app.globalData.temcart["data"] = [newmodel]
        console.log(newmodel)

        wx.navigateTo({
          url: '/xc_lshop/shop/paycore/payinfo?iscart=-1&iswholesale=1'
        })

      }
    },

  }
})